#输入一段语句，然后得到一个表格
#使用一个关键字对应一个元组，该元组存储的是 他的种别码和属性值
#关键字查表
#标识符判断
#常量判断
key_word = {'do':[0,'do'],'end':[1,'end'],'for':[2,'for'],'if':[3,'if'],'print':[4,'print'],'scanf':[40,'scanf'],'while':[5,'while'],'else':[6,'else'],'int':[7,'int'],'float':[8,'float'],'char':[9,'char'],'string':[10,'string']}
const_value = {}
calculation_symbol = {'+':[11,'+'],'-':[12,'-'],'*':[13,'*'],'%':[14,'%'],'/':[15,'/'],'=':[38,'='],'++':[39,'++'],'+=':[45,'+='],'-=':[46,'-='],'*=':[47,'*='],'/=':[48,'/=']}
relation_symbol = {'>=':[16,'>='],'<=':[17,'<='],'==':[18,'=='],'!=':[19,'!='],'<':[34,'<'],'>':[35,'>']}
logic_symbol = {'!':[20,'!'],'&&':[21,'&&'],'||':[22,'||'],'|':[23,'|'],'&':[24,'&'],'<<':[36,'<<'],'>>':[37,'>>']}
boundary_symbol = {'(':[25,'('],')':[26,')'],';':[27,';'],',':[29,','],'{':[30,'{'],'}':[31,'}'],'[':[32,'['],']':[33,']']}
#常 41
#浮点 42
#布尔 43
start_number = 49
class morphology_analysis:
    analysis_form = []
    strPath = ''
    sts = ''
    groupOfs=[]

    def start_up(self):
        self.analysis_form = []
        self.strPath = ''
        self.sts = ''
        self.groupOfs = []
    def readtext(self):
        """
        任务1 :消除注释的影响
        任务2 :消除多余的空格
        返回参数 : 每一行的所有字符组成的字符窜的列表
        """
        self.groupOfs = self.sts.split('\n')
        ans= ''
        idxl = 0
        flag = False
        while idxl < len(self.groupOfs):
            line = self.groupOfs[idxl]
            for idx,c in enumerate(line): #对每一行进行遍历
                if c != ' ' and c != '\n':
                    if c == '/' and idx < len(line) - 1 and (line[idx+1] == '/' or line[idx+1] == '*'):
                        idxt = idxl + 1
                        if line[idx+1] == '*':
                            while idxt < len(self.groupOfs):
                                if line[idxt].find('*/'):
                                    idxt+=1
                                    break
                                idxt+=1
                        idxl = idxt + 1
                        break
                    elif c == '\t':
                        continue
                    else:
                        ans+=c
                elif len(ans) != 0 and (c == ' ' or c == '\n'):
                    if c == '\n' and ans[-1] == ' ':
                        ans = ans[:-1]
                        ans += '\n'
                    elif (c == ' ' and ans[-1] == ' ') or (c == ' ' and ans[-1] == '\n') or (c == '\n' and ans[-1] == '\n'):
                        continue
                    else:
                        ans+=c
            ans += '\n'
            idxl+=1
        groupOfs = ans.split('\n')
        groupOfs.remove('')
        print('符号分割',groupOfs)
        return groupOfs
    def judge_line(self,line:'str'): #将符号彻底的分开
        """
        :param line: 读取到的每一行的字符串
        :return: 每一行的所有分割完之后的结果组成的字符数组
        """
        ans = []
        i,n = 0,len(line)
        symbol = ''
        while i < n:
            if line[i].isalpha():
                symbol += line[i]
                i+=1
                while i < n:
                    if line[i].isalnum() or line[i] == '.':
                        symbol += line[i]
                        i += 1
                    else:
                        break
                ans.append(symbol)
                symbol=''
            elif line[i].isdigit(): #数字
                symbol += line[i]
                i+=1
                while i < n:
                    if line[i].isalnum() or line[i] == '.':
                        symbol += line[i]
                        i+=1
                    else:
                        break
                ans.append(symbol)
                symbol=''
            elif calculation_symbol.get(line[i]) != None or relation_symbol.get(line[i]) != None or logic_symbol.get(line[i]):
                symbol += line[i]
                i += 1
                if calculation_symbol.get(line[i]) != None or relation_symbol.get(line[i]) != None or logic_symbol.get(line[i]):
                    symbol += line[i]
                    i += 1
                ans.append(symbol)
                symbol = ''
            elif boundary_symbol.get(line[i]):
                ans.append(line[i])
                i += 1
                symbol = ''
            elif line[i] == ' ':
                i+=1
            else:
                symbol += line[i]
                i += 1
                while i < n and line[i] != ' ':
                    symbol += line[i]
                    i += 1
                ans.append(symbol)
                symbol=''
        return ans
    def isfloat(self,word):
        twopart = word.split('.')
        if len(word) == 1 and twopart[0].isdigit(): return 1
        if len(twopart) > 2 : return 0
        if twopart[0].isdigit() and (twopart[1].isdigit() or (twopart[1].find('e') == twopart[1].rfind('e') and twopart[1].find('e') != -1)) : return -1

    def reshape_line(self,i:int,line:list):#将这一行的所有出现过的字符，整理为符合条件的项，并加到结果中
        """
        :param i: 行号
        :param line: 该行的所有字符组成的字符串
        :return: 该行词法分析表中出现的所有项构成的字符串
        """
        number = start_number
        for j,word in enumerate(line):
            str = f'{word}'.ljust(15)
            str += f'({i},{j})'.ljust(15)
            if key_word.get(word) != None:
                str += f'{key_word[word]}'.ljust(20)
                str += '关键字'.ljust(15)
            elif boundary_symbol.get(word) != None:
                str += f'{boundary_symbol[word]}'.ljust(20)
                str += '分界符'.ljust(15)
            elif calculation_symbol.get(word) != None:
                str += f'{calculation_symbol[word]}'.ljust(20)
                str += '算术运算符'.ljust(15)
            elif relation_symbol.get(word) != None:
                str += f'{relation_symbol[word]}'.ljust(20)
                str += '关系运算符'.ljust(15)
            elif logic_symbol.get(word) != None:
                str += f'{logic_symbol[word]}'.ljust(20)
                str += '逻辑运算符'.ljust(15)
            elif len(word) and word.isalnum() and word[0].isalpha():
                str += f'{[44,word]}'.ljust(20)
                str += '标识符'.ljust(15)
            elif word.isdigit() or self.isfloat(word) != 0:
                if word == '1' or word == '0':
                    str += f'{[43,word] }'.ljust(20)
                    str += '布尔常量'.ljust(15)
                elif self.isfloat(word) == 1 :
                    str += f'{[41,word] }'.ljust(20)
                    str += '整型常量'.ljust(15)
                elif self.isfloat(word) == -1:
                    str += f'{[42,word] }'.ljust(20)
                    str += '浮点常量'.ljust(15)
                else:
                    str += f'{[number, word]}'.ljust(20)
                    number += 1
                    str += '错误'.ljust(20)
            else:
                str += f'{[number,word]}'.ljust(20)
                number+=1
                str += '错误'.ljust(20)

            self.analysis_form.append(str)

    def generate_form_of_group(self,group:list):
        """
        :param group: 经过预处理之后的字符数组
        :return: None
        """
        for i,s in enumerate(group):
            now_row = self.judge_line(s)
            # 下面查看每一个的类型，构成表
            self.reshape_line(i,now_row)

# h = morphology_analysis()
# h.generate_form_of_group()
#测试程序
# generate_form_of_group(readtext("cppTest.txt"))
# for i in analysis_form:
#     print(i)
# line = "3b = 1"
# print(judge_line(line))